<template>
    <el-form label-width="100px">
        <el-form-item label="SPU名称">
            <el-input v-model="spuInfo.spuName"></el-input>
        </el-form-item>

        <el-form-item label="品牌">
            <el-select v-model="spuInfo.tmId">
                <el-option v-for="item in tmList" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="SPU描述">
            <el-input v-model="spuInfo.description" type="textarea" :rows="4"></el-input>
        </el-form-item>

        <!-- spu图片列表-->
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList" :action="`${baseUrl}/admin/product/upload`"
                list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>

        <!-- 所有销售属性下拉 -->
        <el-form-item label="销售属性">
            <el-select v-model="tempSaleAttr" :placeholder="`还有${unUseSaleAttrList.length}个未选`">
                <el-option v-for="item in unUseSaleAttrList" :key="item.id" :value="`${item.id}:${item.name}`"
                    :label="item.name"></el-option>
            </el-select>
            <el-button :disabled="!tempSaleAttr" type="primary" @click="addSaleAttr">添加销售属性</el-button>
        </el-form-item>

        <!-- spu销售属性表格 -->
        <el-form-item>
            <el-table :data="spuSaleAttrList" border stripe>
                <el-table-column type="index" width="100" align="center" label="序号" />
                <el-table-column label="属性名" prop="saleAttrName" />
                <el-table-column label="属性值名称列表">
                    <template v-slot="{ row }">
                        <!-- 属性值tag -->
                        <el-tag type="success" closable @close="" v-for="item in row.spuSaleAttrValueList"
                            :key="item.id">{{ item.saleAttrValueName }}</el-tag>
                        <!-- 输入框数据属性值 -->
                        <el-input v-if="!row.isEdit" ref="inputEle" v-model="row.inputValue"></el-input>
                        <!-- 点击按钮切换状态 -->
                        <el-button v-else="" type="info" size="small" @click="changeToEdit(row)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ $index }">
                        <el-button type="danger" icon="ele-Delete" @click="spuSaleAttrList.splice($index, 1)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>

        <!-- 保存取消按钮 -->
        <el-form-item>
            <el-button type="primary" @click="">保存</el-button>
            <el-button @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import type { SpuInfoType } from "@/api/spu";
import { defineComponent } from "vue";

export default defineComponent({
    name: "SpuFrom",
});
</script>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue"
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps } from 'element-plus'
import { requestAllTmList, type TmListType } from "@/api/trademark"
import {
    requestBaseSaleAttrList,
    requestSpuImgList,
    requestSpuSaleAttrList,
    type BaseSaleAttrListType,
    type SpuImageListType,
    type SpuSaleAttrItemType,
    type SpuSaleAttrListType,
} from "@/api/spu"
const baseUrl = import.meta.env.VITE_API_URL

//1.接收props传值
const props = defineProps<{
    spuInfo: SpuInfoType
}>()

//2.接收自定义事件
const emit = defineEmits<{
    (event: "setState", state: number, row?: SpuInfoType): void
}>()


//定义数据保存初始化请求回来的数据
const tmList = ref<TmListType[]>([])
const allSaleAttrList = ref<BaseSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])
//定义函数发送初始化请求
const getInitData = async () => {
    try {
        if (props.spuInfo.id) {
            //修改发送4个请求
            const promise1 = requestAllTmList()
            const promise2 = requestBaseSaleAttrList()
            const promise3 = requestSpuImgList(props.spuInfo.id)
            const promise4 = requestSpuSaleAttrList(props.spuInfo.id)

            //一次发送4个请求
            const result = await Promise.all([promise1, promise2, promise3, promise4])

            //保存到响应式数据中
            tmList.value = result[0]
            allSaleAttrList.value = result[1]
            spuImageList.value = result[2]
            //处理图片列表数据
            spuImageList.value.forEach((item) => {
                item.name = item.imgName
                item.url = item.imgUrl
            })
            spuSaleAttrList.value = result[3]
            //处理销售属性列表数据
            spuSaleAttrList.value.forEach((item) => {
                //添加数据保存当前行的状态
                item.isEdit = false
                //添加数据保存当前行输入框状态
                item.inputValue = ""
            })
        } else {
            //添加发送2个请求
            const result1 = await requestAllTmList()
            tmList.value = result1
            const result2 = await requestBaseSaleAttrList()
            allSaleAttrList.value = result2
        }
    } catch (error) {
        //失败提示
        ElMessage.error("初始化请求失败!")
    }
}
//3.初始化请求需要的数据
onMounted(() => {
    getInitData()
});


//4.计算未使用的所有销售属性列表
const unUseSaleAttrList = computed(() => {
    return allSaleAttrList.value.filter((item) => {
        return !spuSaleAttrList.value.some((item2) => {
            return item.name === item2.saleAttrName
        })
    })
})

//定义数保存临时销售属性
const tempSaleAttr = ref("")
//5.添加销售属性的回调
const addSaleAttr = () => {
    //拿到基础销售属性id和名字
    const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":")
    //创建一条销售属性数据
    const newSaleAttr = {
        baseSaleAttrId: +baseSaleAttrId,
        saleAttrName: saleAttrName,
        spuSaleAttrValueList: []
    }
    //插入到spu销售属性列表
    spuSaleAttrList.value.push(newSaleAttr)
    //清空临时销售属性
    tempSaleAttr.value = ""
}

//获取Input实例
const inputEle = ref()
//6.点击属性值按钮的回调
const changeToEdit = (row: SpuSaleAttrItemType) => {
    //切换编辑状态
    row.isEdit = true
    //获取焦点

}







//照片墙逻辑
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
</script>